GGplot avancé

recap ggplot

mpg %>% 
  ggplot()+
  aes(x= cty, y = hwy, color = manufacturer)+
  geom_point()+
  facet_wrap(~drv)

plot de base pour travailler

base <- iris %>% 
  ggplot() +
  aes(x = Sepal.Length, y = Sepal.Width,
      color = Species, size = Petal.Width)+
  geom_point()

base

coord_*

coord_flip()

ça inverse les axes

base + coord_flip()

coord_cartesian()

changer les limites ou autre propriéé des coordonnées

base + coord_cartesian(xlim = c(6,7), ylim = c(2.5,3))

coord_fixed() and coord_equal()

base_mpg <- mpg %>% 
  ggplot() +
  aes(cty, hwy)+
  geom_point() +
  geom_abline(slope = 1, intercept = 0, color = "red", linetype = "dashed")
base_mpg

créer des coordoonées égales – on obtient le control sur le ratio des unités de l’axe X et de l’axe Y.

base_mpg + coord_equal(ratio = 1)

coord_fixed()

base_mpg + coord_fixed(ratio = 2)

coordonnées polaires

  • coordonnée cartesienne: x, y -> x c’est la position horizontale, et y la position verticale.

  • coordonnée polaire: x, y -> x c’est la distance du centre; y c’est l’angle.

base + coord_polar()

camemberts!! pie charts

  • un pie chart c’est juste une barre en coordonnées polaires!

on commence par un graphique en barre

barre <- mpg %>% 
  ggplot()+
  aes(x = "", y = class, fill = class)+
  geom_col()

barre

transform en pie chart!

barre + coord_polar(theta = "y")

example de coord_polar avec babynames

  • évolution des “Mary”
library(babynames)

linear <- babynames %>% 
  filter(name %in% c("Mary","Emily") & sex == "F") %>% 
  ggplot()+
  aes(x = year, y = prop, color = name)+
  geom_line()
linear

version polaire

linear + coord_polar()

chart en radar avec coord_polar

créer des données sur deux villes françaises pour les comparer

df <- tibble(ville = c("Grenoble", "Paris"),
             taille = c(2, 5),
             distance_mer = c(3, 2),
             distance_montagne = c(0, 5),
             sympa = c(5, 0),
             riche = c(3, 4))
  1. tidy the data fram -> une variable par colonne et une observation par ligne
df_tidy <- df %>% 
  pivot_longer(-ville, names_to = "caracteristique", values_to = "note")
df_tidy
## # A tibble: 10 × 3
##    ville    caracteristique    note
##    <chr>    <chr>             <dbl>
##  1 Grenoble taille                2
##  2 Grenoble distance_mer          3
##  3 Grenoble distance_montagne     0
##  4 Grenoble sympa                 5
##  5 Grenoble riche                 3
##  6 Paris    taille                5
##  7 Paris    distance_mer          2
##  8 Paris    distance_montagne     5
##  9 Paris    sympa                 0
## 10 Paris    riche                 4
  1. plot en linéaire
linear <- df_tidy %>% 
  ggplot()+
  aes(x= caracteristique, y = note, color = ville, group = ville)+
  geom_line()
linear

  1. on fait un radar avec coord_polar()
linear + coord_polar(direction = -1, clip = "off")

scale_*_*

base + scale_color_grey(start = 0.2, end = 0.8)

base + scale_color_brewer(palette = "Pastel1")

base + scale_color_viridis_d(option = "magma")

base + scale_color_manual(values = c("pink", "#7fd7f7", "#bdffa5"))

continuous scales

example avec couleur continue

df <- tibble(x = rnorm(1000, mean = 10, sd = 5),
             y = runif(1000, min = 5, max = 7),
             score = rnorm(1000, mean = 0, sd = 2))

base_rnorm <- df %>% 
  ggplot()+
  aes(x= x, y = y, color = score)+
  geom_point()

base_rnorm

on n’y voit rien du tout avec les couleurs par défaut!!!

changer le gradient; 2 point

base_rnorm + scale_color_gradient(low = "red", high = "green")

gradient avec 3 points

base_rnorm + scale_color_gradient2(low = "red", mid = "grey", high = "green")

gradient avec N passages

base_rnorm + scale_color_gradientn(colors = c("red", "yellow", "orange", "blue", "green"))

entre continue et discret on a les “binned”

base_rnorm+ scale_color_binned()

changing other things

base + scale_size_continuous(range = c(1, 12))

fill vs color

barres!

barres2 <- mpg %>% 
  ggplot()+
  aes(x = manufacturer, fill = manufacturer)+
  geom_bar()

appearance as mapped vs non-mapped

  • tout ce qui est mappé à une variable est geré par les fonctions scale_*_*
  • si ce n’est pas mappé, vous pouvez changer directement
barres2

 mpg %>% 
  ggplot()+
  aes(x = manufacturer, fill = manufacturer, color = manufacturer)+
  geom_bar()+
  geom_hline(yintercept = 15, color = "red")

themes

base + theme_minimal()

ggthemes

install.packages("ggthemes")
## Installing package into '/usr/local/lib/R/site-library'
## (as 'lib' is unspecified)
library(ggthemes)

base + theme_solarized_2()

à la main

base +
  theme(legend.position = "none",
        panel.background = element_rect(fill = "yellow"),)

titres, lignes, annotations

theme_paolo <- theme(plot.caption.position = "plot",
        plot.caption = element_text(size = 5, face = "italic"),
        plot.title = element_text(face = "bold", size = 30, colour = "red"), 
        plot.subtitle = element_text(face = "italic"))

base +
  labs(title = "Grand titre", subtitle = "on explique des choses",
       caption = "by @paolocrosetto", alt = "texte qui décrit le plot")+
 theme_paolo

lignes de référence

base_rnorm +
    labs(title = "Notes BAC 2021", 
         x = "note")+ 
  coord_cartesian(xlim = c(0,20))+
  geom_vline(xintercept = 10, color = "red")+
  geom_hline(yintercept = 5.5, color = "green")+
  geom_abline(slope = 0.5, intercept = 5, linetype = "dashed", size = 2)  # y = ax + b

autres annotations

base_rnorm +
  annotate("text", x = 0, y = 6.8, label = "BONJOUR")+
  annotate("segment", x = 0, xend = 10, y = 6, yend = 6.5, color = "green", size = 3)

base +
  annotate("text", x = 4.5, y = 4.3, label = "SETOSA")+
  annotate("segment", x = 4.5, y = 2.4, xend = 7, yend = 4.4, color = "red")

saving a plot

fonction ggsave